require 'map_editor/tile_panel'
module EventEditor
  class CharacterImagePanel < MapEditor::TilePanel
    def initialize(controler)
      super(2)
      @scroll_box = Editor::ScrollBox.new(1, 1, 1, 1) do
        self.render
        @scroll_box.set_size(@scroll_box.width, @scroll_box.height)
        #p @scroll_box.content_height
        #p @scroll_box.h_scrollbar.adjustment.upper
      end
      @controler = controler
      @controler.target = self
      self.set_panel
      self.set_signals
      self.load(nil, 1, 1)
    end
    
    def grid_width
      @scroll_box.grid_width / self.zoom
    end
    
    def grid_height
      @scroll_box.grid_height / self.zoom
    end
    
    def load(texture, grid_width, grid_height, sx = 0, sy = 0)
      @texture = texture
      
      @scroll_box.grid_width = grid_width * self.zoom
      @scroll_box.grid_height = grid_height * self.zoom
      @controler.sx = sx
      @controler.sy = sy
      if @texture
        @buff = texture.clone
        tw = @texture.width * self.zoom
        th = @texture.height * self.zoom
        unless @dst_texture && tw == @dst_texture.width && th == @dst_texture.height
          @dst_texture = Texture.new(tw, th)
        end

        @scroll_box.set_client_size(@dst_texture.width, @dst_texture.height)

      else
        @scroll_box.set_client_size(1, 1)
      end
      
      @scroll_box.refresh_scrollbars
      @scroll_box.on_resize
      
      self.render
    end
    
    def on_left_down(e)
      super(e)
    end
    
    def render
      area = @scroll_box.content_image

      return unless area.window
      if @texture
        @buff.clear

        @buff.render_texture(@texture, -self.scroll_x / (self.zoom), -self.scroll_y / (self.zoom), :blend_type => :none)
        @controler.render(@buff)
        @dst_texture.render_texture(@buff, 0, 0, :scale_x => self.zoom, :scale_y => self.zoom, :blend_type => :none)
        tw, th = @dst_texture.width, @dst_texture.height
        
        buf = Gdk::Pixbuf.new(@dst_texture.dump('rgb'), Gdk::Pixbuf::ColorSpace.new(Gdk::Pixbuf::ColorSpace::RGB), false, 8, tw, th, tw * 3)
        gc = Gdk::GC.new(area.window) 
        area.window.draw_pixbuf(gc, buf, 0, 0, 0, 0, buf.width, buf.height, Gdk::RGB::DITHER_NONE, 0, 0)
      else
        area.window.clear
      end
    end
  end
end